package org.yunai.swjg.server.core.heartbeat;

import java.util.ArrayList;
import java.util.List;

/**
 * 心跳任务执行器
 * User: yunai
 * Date: 13-5-24
 * Time: 上午9:44
 */
public class HeartbeatTaskExecutorImpl implements HeartbeatTaskExecutor {

    private List<TaskTimerPair> tasks = new ArrayList<>(1);

    @Override
    public void submit(HeartbeatTask task) {
        tasks.add(new TaskTimerPair(task, new MilliHeartbeatTimer(task.period())));
    }

    @Override
    public void heartBeat() {
        for (TaskTimerPair task : tasks) {
            if (task.timer.timeUp()) {
                task.task.run();
                task.timer.nextRound();
            }
        }
    }

    private static class TaskTimerPair {

        public final HeartbeatTask task;
        public final HeartbeatTimer timer;

        private TaskTimerPair(HeartbeatTask task, HeartbeatTimer timer) {
            this.task = task;
            this.timer = timer;
        }
    }
}
